package cn.miao.hrm.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpUtil;
import cn.miao.constant.BaseConst;
import cn.miao.hrm.domain.Login;
import cn.miao.hrm.domain.LoginMeal;
import cn.miao.hrm.dto.LoginAgencyDto;
import cn.miao.hrm.mapper.LoginMapper;
import cn.miao.hrm.mapper.LoginMealMapper;
import cn.miao.hrm.service.ILoginService;
import cn.miao.util.AjaxResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author MiaoDaWei
 * @since 2021-11-22
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    @Value("${oauth2.url.token}")
    private String OAUTH2_TOKEN;

    @Value("${oauth2.url.refreshtoken}")
    private String OAUTH2_REFRESH_TOKEN;
    @Autowired
    private LoginMealMapper loginMealMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 保存登录和角色
     *
     * @param dto 登录
     * @return {@link AjaxResult}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveLoginAndRole(LoginAgencyDto dto) {

        Date date = new Date();

        //先保存 t_login表
        Login login = dto.getLogin();
        login.setType(BaseConst.LoginState.STATUS_TYPE_EMPL);
        login.setPassword(passwordEncoder.encode(login.getPassword()));
        insert(login);

        //保存t_login_meal 登录和套餐的中间表
        DateTime expireTime = DateUtil.offsetDay(date, 7);
        LoginMeal loginMeal = new LoginMeal();
        loginMeal.setLoginId(login.getId());
        loginMeal.setMealId(Convert.toLong(dto.getMealId()));
        loginMeal.setExpireDate(expireTime);
        loginMeal.setState(BaseConst.LoginMealState.STATUS_WAIT_PAY);
        loginMealMapper.insert(loginMeal);

        return AjaxResult.me().setResultObj(login.getId());
    }

    /**
     * 登录
     *
     * @return {@link AjaxResult}
     * @param map
     */
    @Override
    public AjaxResult login(Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        String type = map.get("type");

        //组合拼接获取token的路径
        String clientId =CharSequenceUtil.EMPTY;
        String clientSecret = "123";
        //为1表示后台登录
        if ("1".equals(type)) {
            clientId = "admin";
        }else{
            clientId = "website";
        }

        //组合
        String passwordToken = CharSequenceUtil.format(OAUTH2_TOKEN, clientId, clientSecret, username, password);
        //发起HTTP网络获取
        String post = HttpUtil.post(passwordToken, "");
        Map parseObject = JSONObject.parseObject(post, Map.class);
        return AjaxResult.me().setResultObj(parseObject);
    }

    @Override
    public AjaxResult refresh(String refreshToken, Integer type) {
//组合拼接获取token的路径
        String clientId;
        String clientSecret = "123";
        //为1表示后台登录
        if (type.compareTo(1) == 0) {
            clientId = "admin";
        } else {
            clientId = "website";
        }

        //组合
        String passwordToken = CharSequenceUtil.format(OAUTH2_REFRESH_TOKEN,refreshToken, clientId, clientSecret);
        //发起HTTP网络获取
        String post = HttpUtil.post(passwordToken, "");
        Map parseObject = JSONObject.parseObject(post, Map.class);
        return AjaxResult.me().setResultObj(parseObject);
    }
}
